﻿
using COSXML;
using COSXML.Auth;
using COSXML.Transfer;
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBUpload
{
    class Program
    {

        static Logger logger = LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            logger.Debug("开始执行数据库文件上传！");
            Console.WriteLine("开始执行数据库文件上传！");
            UploadDBFile();
            logger.Debug("执行数据库文件上传完毕！");
            Console.WriteLine("执行数据库文件上传完毕！"); 

        }
        static List<string> list = new List<string>();//定义list变量，存放获取到的路径
        public static List<string> getPath(string path)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] fil = dir.GetFiles();
            DirectoryInfo[] dii = dir.GetDirectories();
            foreach (FileInfo f in fil)
            {
                list.Add(f.FullName);//添加文件的路径到列表
            }
            //获取子文件夹内的文件列表，递归遍历
            foreach (DirectoryInfo d in dii)
            {
                getPath(d.FullName);
                list.Add(d.FullName);//添加文件夹的路径到列表
            }
            return list;
        }
        /// <summary>
        /// 腾讯云oss
        /// </summary>
        public static  void UploadDBFile()
        {
            
            string appid = ConfigurationManager.AppSettings["AppId"];
            string region = ConfigurationManager.AppSettings["COS_REGION"];
            string secretId = ConfigurationManager.AppSettings["SecretId"] ;
            string secretKey = ConfigurationManager.AppSettings["SECRET_KEY"];
            string bucket = ConfigurationManager.AppSettings["Bucket"]; //存储桶，格式：BucketName-APPID 
            long durationSecond = 600;

            CosXmlConfig config = new CosXmlConfig.Builder()
              .IsHttps(true)  //设置默认 HTTPS 请求
              .SetRegion(region)  //设置一个默认的存储桶地域
              .SetDebugLog(true)  //显示日志
              .Build();  //创建 CosXmlConfig 对象


            QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);
            CosXml cosXml = new CosXmlServer(config, cosCredentialProvider);
            // 初始化 TransferConfig
            TransferConfig transferConfig = new TransferConfig();
            // 初始化 TransferManager
            TransferManager transferManager = new TransferManager(cosXml, transferConfig);     
            // 上传对象 
            try
            {
                DirectoryInfo dir = new DirectoryInfo(@"E:\db_backup");
                FileInfo[] fil = dir.GetFiles();
                DirectoryInfo[] dii = dir.GetDirectories();
                DateTime dt = DateTime.Now;
                foreach (FileInfo f in fil)
                {
                    if (f.Extension.Equals(".bak") && f.CreationTime.Date == dt.Date)
                    {
                        string filekey = string.Format("dbfiles/{0}/{1}/{2}", dt.Year, dt.Month, f.Name);
                        var uploadFileBytes = new byte[f.Length];
                        COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, filekey);
                        uploadTask.SetSrcPath(f.FullName);
                        uploadTask.progressCallback = delegate (long completed, long total) {
                            
                        };
                        var task= transferManager.UploadAsync(uploadTask);
                        task.Wait();
                        var result = task.Result;
                        logger.Debug(result.ToString());
                        logger.Debug(f.Name);
                    }
                } 
            }
            catch (Exception ex)
            {
               logger.Error(ex);
            }

             

        }
    }
}
